// https://www.lintcode.com/problem/convert-binary-tree-to-linked-lists-by-depth/

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    /**
     * @param root the root of binary tree
     * @return a lists of linked list
     */
    public List<ListNode> binaryTreeToLists(TreeNode root) {
        // Write your code here
        List<ListNode> ret = new ArrayList<>();
        List<TreeNode> curr = new ArrayList<>();
        List<TreeNode> next = new ArrayList<>();
        if (root != null) {
            curr.add(root);
            while (!curr.isEmpty()) {
                ListNode head = null, tail = null;
                for (TreeNode node : curr) {
                    ListNode ln = new ListNode(node.val);
                    if (null == head) {
                        head = ln;
                    }
                    else {
                        tail.next = ln;
                    }
                    tail = ln;
                    if (node.left != null) {
                        next.add(node.left);
                    }
                    if (node.right != null) {
                        next.add(node.right);
                    }
                }
                ret.add(head);
                curr = next;
                next = new ArrayList<>();
            }
        }
        return ret;
    }
}